package com.rpc.demo.tomcat;

import org.apache.catalina.Engine;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Server;
import org.apache.catalina.Service;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.startup.Tomcat;

public class HttpServer {
	/**
	 * <Server port="8005" shutdown="SHUTDOWN">
	 *      <Service name="Catalina">
	 *          <Connection port="8080" protocol="HTTP/1.1"
	 *                  connectionTimeout="20000"
	 *                  redirectPort="8443"
	 *                  URLEncoding="UTF-8"/>
	 *          <Engine name="Catalina" defaultHost="localhost">
	 *              <Host name="localhost" appBase="webapps" unpackWaRs="true" autoDeploy="true">
	 *                  <Context path="" doBase="WORKDIR" reloabale="true"></Context>
	 *              </Host>
	 *          </Engine>
	 *      </Service>
	 * </Server>
	 */

	/**
	 * 启动服务
	 */
	public void start(String hostname,int port){
		//实例一个tomcat
		Tomcat tomcat = new Tomcat();
		//构建server
		Server server = tomcat.getServer();
		//获取service
		Service service = server.findService("Tomcat");
		//构建connector
		Connector connector = new Connector();
		connector.setPort(port);
		connector.setURIEncoding("UTF-8");
		//构建Engine
		StandardEngine engine = new StandardEngine();
		engine.setDefaultHost(hostname);
		//构建Host
		StandardHost standardHost = new StandardHost();
		standardHost.setName(hostname);
		//构建context
		String contextPath="";
		StandardContext context = new StandardContext();
		context.setPath(contextPath);
		context.addLifecycleListener(new Tomcat.FixContextListener());//生命周期监听器
		//然后按照server.xml,一层层把子节点添加到父节点
		standardHost.addChild(context);
		engine.addChild(standardHost);

		service.setContainer(engine);
		service.addConnector(connector);

		//tomcat是一个servlet,设置路径与映射
		tomcat.addServlet(contextPath,"dispatcher",new DispatcherServlet());
		context.addServletMappingDecoded("/*","dispatcher");

		try {
			tomcat.start(); //启动tomcat
			tomcat.getServer().await();//接受请求
		} catch (LifecycleException e) {
			e.printStackTrace();
		}

	}



}
